// eslint-disable-next-line no-unused-vars
import VXETable, { Column } from 'vxe-table'
import NewImage from '../../../components/NewImage'
import { ImgUrl } from '@Components/assets/js/config'
import { isExternalImg } from '@Components/assets/js/common'
import createBem from '@Components/assets/js/utils/bem'
import { tableNamespace } from '../../../config'
import './index.scss'

const Bem = createBem(`${tableNamespace}__image`)

function handleImageUrl(path, external) {
  const prefix = external ? '' : ImgUrl
  if (external || isExternalImg(path)) {
    return path
  }
  return prefix + path
}

VXETable.renderer.add('Image', {
  renderDefault(h, renderOpts, params) {
    const { row, column } = params
    const { $tableInstance, options = {} } = renderOpts
    const { external, objectKey } = options
    const images = row[column.property]

    let imageList = []
    if (images instanceof Array) {
      imageList = images.map(i => {
        return handleImageUrl(objectKey ? i[objectKey] : i, external)
      })
    } else {
      imageList = [handleImageUrl(images, external)]
    }

    function handleShowViewer() {
      $tableInstance.updateViewer(imageList)
    }
    function handleMouseEnter(event) {
      if (imageList.length !== 1) return
      $tableInstance.updateToolTipDom(event)
      $tableInstance.isHover = true
    }
    function handleMouseLeave() {
      if (imageList.length !== 1) return
      $tableInstance.isHover = false
    }
    return [
      <div class={Bem()}>
        <NewImage
          images={imageList}
          onMouseenter={handleMouseEnter}
          onMouseleave={handleMouseLeave}
          onClick={handleShowViewer}
        />
      </div>
    ]
  }
})

/** @type { Column } */
export const options = {
  showOverflow: 'ellipsis',
  align: 'center'
}
